<template>
  <div class="lyric" ref="lyricRef">
    <div 
      class="lyric-wrapper" 
      :style="{ transform: `translateY(${offset}px)` }"
    >
      <p 
        v-for="(line, index) in parsedLyric" 
        :key="index"
        :class="{ active: currentLine === index }"
        class="lyric-line"
      >
        {{ line.text }}
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'

interface LyricLine {
  time: number
  text: string
}

const props = defineProps<{
  lyric: string
  currentTime: number
}>()

const lyricRef = ref<HTMLElement>()
const currentLine = ref(0)

// 解析歌词
const parsedLyric = computed(() => {
  if (!props.lyric) return []
  
  const lines = props.lyric.split('\n')
  const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/
  
  return lines
    .map(line => {
      const match = timeRegex.exec(line)
      if (!match) return null
      
      const [, minutes, seconds, milliseconds] = match
      const time = parseInt(minutes) * 60 + parseInt(seconds) + parseInt(milliseconds) / 1000
      const text = line.replace(timeRegex, '').trim()
      
      return { time, text }
    })
    .filter((line): line is LyricLine => line !== null)
    .sort((a, b) => a.time - b.time)
})

// 计算偏移量
const offset = computed(() => {
  if (!lyricRef.value) return 0
  const lineHeight = 32 // 每行歌词高度
  const middlePos = lyricRef.value.clientHeight / 2
  return middlePos - currentLine.value * lineHeight
})

// 监听当前时间更新当前行
watch(() => props.currentTime, (time) => {
  const index = parsedLyric.value.findIndex((line, i) => {
    const nextLine = parsedLyric.value[i + 1]
    return line.time <= time && (!nextLine || nextLine.time > time)
  })
  
  if (index !== -1) {
    currentLine.value = index
  }
})
</script>

<style scoped>
.lyric {
  height: 400px;
  overflow: hidden;
  mask-image: linear-gradient(
    180deg,
    transparent 0%,
    #000 10%,
    #000 90%,
    transparent 100%
  );
}

.lyric-wrapper {
  transition: transform 0.3s ease;
}

.lyric-line {
  height: 32px;
  line-height: 32px;
  text-align: center;
  transition: all 0.3s;
  color: #666;
}

.lyric-line.active {
  color: var(--primary-color);
  font-size: 16px;
  font-weight: bold;
}
</style> 